package com.geek688.auxiliarytool.ui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

import com.geek688.auxiliarytool.bean.Log;
import com.geek688.auxiliarytool.bean.TableInfo;
import com.geek688.auxiliarytool.config.Config;
import com.geek688.auxiliarytool.util.DBUtil;
import com.geek688.auxiliarytool.util.FreeMarkUtil;
import com.geek688.auxiliarytool.util.LogUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SQLUI extends JFrame implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	//工具版本
	private static final String version = "版本v3.0";
	//项目根路径
	private JFileChooser outPath = new JFileChooser();
	//模板路径
	private JFileChooser templatePath = new JFileChooser();
	//输出框
	private JTextArea area = new JTextArea();
	//获取的全部表
	private List<String> allTablesList = new LinkedList<>();
	//用户选中的表
    private List<String> checkedList = new LinkedList<>();
	private JComboBox<String> packageNameBox = new JComboBox<>();
	private JPanel check = new JPanel();
	private JScrollPane scrollcheck = new JScrollPane(check);
	
	JCheckBox checkBtn = null;
	private JComboBox<String> templatePathBox = new JComboBox<>();
//	private JTextField templatePathTextField= null;//2020-03-26
	private JTextField outPathTextField= null;
    private boolean enableFlag = false;
    private boolean checkFlag = false;
    private DataSource dataSource = null;
    private FreeMarkUtil mark = null;
//    private List<String> command = Arrays.asList(
//    		"springboot","traditional"
//    );
    private List<String> defaultTemplate = Arrays.asList(
    		"springModelTemplate.ftl",
    		"springControllerTemplate.ftl",
    		"springServiceTemplate.ftl", 
    		"springbootModelTemplate.ftl",
    		"springbootControllerTemplate.ftl",
    		"springbootServiceTemplate.ftl",
    		"jspAddTemplate.ftl",
    		"jspEditTemplate.ftl",
    		"jspListTemplate.ftl",
    		"vueAddOrEditTemplate.ftl",
    		"vueIndexTemplate.ftl"
    );
    /**
     * @Title drawUI
     * @description 绘制操作界面
     * author geek
     * @param tabPanel
     */
	public void drawUI(JTabbedPane tabPanel) {

        JPanel panel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JPanel filePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));

        //读取上一次操作日志
        Log readLog = LogUtil.readLog();
        outPathTextField = new JTextField(readLog.getProjectPath());
        JButton fileBtn = new JButton("项目根路径");
        
        fileBtn.setActionCommand("open");fileBtn.addActionListener(this);
        outPathTextField.setPreferredSize(new Dimension(250, 25));
        filePanel.add(fileBtn);
        filePanel.add(outPathTextField);
        JButton templateBtn = new JButton("模板路径");
        templateBtn.setActionCommand("template");templateBtn.addActionListener(this);
        
        defaultTemplate.forEach(template->{
        	templatePathBox.addItem("内置模板-"+template);
        });
        Set<String> templatelist = readLog.getTemplatePath();
        templatelist.forEach(templatePath->{
        	templatePathBox.addItem(templatePath);
        });
        templatePathBox.addItem("清空列表");
        templatePathBox.setPreferredSize(new Dimension(280, 25));
        templatePathBox.setEditable(true);
        templatePathBox.setActionCommand("templateCheckBox");templatePathBox.addActionListener(this);
        
//        templatePathTextField = new JTextField(readLog.getTemplatePath());//2020-03-26
//        templatePathTextField.setPreferredSize(new Dimension(250, 25)); //2020-03-26
        filePanel.add(templateBtn);
//        filePanel.add(templatePathTextField);//2020-03-26
        filePanel.add(templatePathBox);
//        filePanel.add(packageName);filePanel.add(packagenameText);
        panel5.add(filePanel);
        JPanel packagePanel = new JPanel();
        packagePanel.add(new JLabel("项目包名："));
//        packagenameText = new JTextField(m.get("package"));
//        packagenameText.setPreferredSize(new Dimension(200, 25));
		Set<String> list = readLog.getPackageName();
        list.forEach(packName->{
        	packageNameBox.addItem(packName);
        });
        if (list.size()>1) {
        	packageNameBox.addItem("清空列表");
		}
        packageNameBox.setPreferredSize(new Dimension(200, 25));
        packageNameBox.setEditable(true);
        packageNameBox.setActionCommand("checkBox");packageNameBox.addActionListener(this);
        packagePanel.add(packageNameBox);
        panel5.add(packagePanel);
        
        JPanel accountPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
//        accountPanel.setPreferredSize(new Dimension(790, 30));
        JButton getBtn = new JButton("获取表");getBtn.setActionCommand("get");getBtn.addActionListener(this);
        JButton sqlBtn = new JButton("设置");sqlBtn.setActionCommand("sql");sqlBtn.addActionListener(this);
        accountPanel.add(sqlBtn);accountPanel.add(getBtn);
        JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        JButton runBtn = new JButton("导出表结构");runBtn.setActionCommand("run");runBtn.addActionListener(this);
        JButton beanBtn = new JButton("运行");beanBtn.setActionCommand("bean");beanBtn.addActionListener(this);
        checkBtn = new JCheckBox("全选");
        checkBtn.setActionCommand("check");checkBtn.addActionListener(this);
        JButton externTemplateBtn = new JButton("FreeMark");externTemplateBtn.setActionCommand("externTemplate");externTemplateBtn.addActionListener(this);
        btnPanel.add(externTemplateBtn);btnPanel.add(runBtn);btnPanel.add(beanBtn);btnPanel.add(checkBtn);
        
        panel5.add(accountPanel);
        panel5.add(btnPanel);
        scrollcheck.setPreferredSize(new Dimension(770, 150));
        scrollcheck.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panel5.add(scrollcheck);
//	    area.setFont(new Font("宋体",Font.LAYOUT_LEFT_TO_RIGHT,14));
        area.setLineWrap(true);//自动换行
        area.setForeground(Color.RED);
        area.setBorder(BorderFactory.createLineBorder(Color.gray,1));//边框
        
        JScrollPane scrollPane = new JScrollPane(area);        
        //分别设置水平和垂直滚动条自动出现
//	    panel3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//	    panel3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
      //分别设置水平和垂直滚动条总是出现
//	    panel3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setViewportView(area);
        scrollPane.setPreferredSize(new Dimension(770, 260));
        panel5.add(scrollPane);
        JPanel panel = new JPanel(new GridLayout(1, 2));
        panel.setPreferredSize(new Dimension(770, 15));
        panel.add(new JLabel(version,JLabel.RIGHT));
        panel5.add(panel);
        tabPanel.addTab("代码辅助工具", panel5);
	}
	/**
	 * 事件监听
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		//设置项目根路径
		if(e.getActionCommand().equals("open")) {
			outPath.setCurrentDirectory(new File(outPathTextField.getText()));
			outPath.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			outPath.showOpenDialog(this);
			File f = outPath.getSelectedFile();//使用文件类获取选择器选择的文件
			String s = f.getAbsolutePath().trim();//返回路径名
			outPathTextField.setText(s);
			Log readLog = LogUtil.readLog();
			readLog.setProjectPath(s);
			LogUtil.writeLog(readLog);
		}
		//设置选用的模板路径
		if(e.getActionCommand().equals("template")) {
			templatePath.setCurrentDirectory(new File((String) templatePathBox.getSelectedItem()));
//			templatePath.setCurrentDirectory(new File(templatePathTextField.getText()));//2020-03-26
			templatePath.setFileSelectionMode(JFileChooser.FILES_ONLY);
			templatePath.setFileFilter(new FileFilter() {
				@Override
				public String getDescription() {
					return "*"+Config.SUFFIX_FTL;
				}
				@Override
				public boolean accept(File file) {
					 String name = file.getName();  
				     return file.isDirectory() || name.toLowerCase().endsWith(Config.SUFFIX_FTL) ;  // 仅显示目录和ftl文件
				}
			});
			templatePath.showOpenDialog(this);
			File f = templatePath.getSelectedFile();//使用文件类获取选择器选择的文件
			if (f==null) {
				f = new File("");
			}
			String templatePath = f.getAbsolutePath().trim();//返回路径名
//			templatePathTextField.setText(templatePath);2020-03-26
			
//			Log readLog = LogUtil.readLog();
			if (StringUtils.isNotBlank(templatePath)&&!templatePath.startsWith("内置模板")&&!templatePath.equals(new File("").getAbsolutePath())) {
				templatePathBox.removeAllItems();
				defaultTemplate.forEach(template->{
		        	templatePathBox.addItem("内置模板-"+template);
		        });
				Log readLog = LogUtil.readLog();
				Set<String> templatelist = readLog.getTemplatePath();
		        templatelist.forEach(templatePa->{
		        	templatePathBox.addItem(templatePa);
		        });
				templatePathBox.addItem(templatePath);
				int index = templatePathBox.getItemCount()-1;
				templatePathBox.setSelectedIndex(index);
				templatePathBox.addItem("清空列表");
				SwingUtilities.updateComponentTreeUI(templatePathBox);
				LogUtil.writeTemplateLog(templatePath);
			}
			
//			LogUtil.writeLog(readLog);
			mark = new FreeMarkUtil(f);
//			filelist.clear();
//			List<String> list = SQLUI.getFileList(new File(templatePath));
//			JOptionPane.showMessageDialog(this,"本次扫描到模板文件 "+list.size()+" 个!");
			
		}
		//按照模板文件 创建文件
		if(e.getActionCommand().equals("bean")) {
			this.checkTemplate();
			this.getCheckedTables();
			new Thread(()->{
				if(enableFlag) {
					mark.setArea(area);
					mark.createModel(checkedList);
				}
			}).start();
		}
		//FreeMark模板自定义参数设置
		if(e.getActionCommand().equals("externTemplate")) {
			//获取freemark自定义参数设置面板
			FreeMarkSettingUI.getInstance(area);
		}
		//导出excel文件
		if(e.getActionCommand().equals("run")) {
			String path = outPathTextField.getText();
			if(StringUtils.isBlank(path)){
				JOptionPane.showMessageDialog(this,"请选择保存路径");
				return ;
			}
			//清空输出台
			area.setText("");
			this.getCheckedTables();
            if (enableFlag) {
				Runnable run=()->{
					createExcel(checkedList);
					SwingUtilities.updateComponentTreeUI(area);	
				};
				new Thread(run).start();
			}
		}
		//获取表
		if(e.getActionCommand().equals("get")) {
			allTablesList.clear();
			check.removeAll();
			checkedList.clear();
			if(dataSource == null) {
				JOptionPane.showMessageDialog(this,"请设置数据库链接!");//弹出对话框,显示选择结
				return ;
			}
			if(enableFlag) {
				this.getAllTables();
			}
			scrollcheck.setVisible(false);
			new Thread(()->{
				try {
					TimeUnit.MILLISECONDS.sleep(100);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				//注意不能直接执行下两步，获取滚动棒获取的是上一次的，直接设置的滚动条也是按上一次，会导致总是显示倒数第二行！需等待一段时间才能获取这次滚动棒长度
				JScrollBar jscrollBar = scrollcheck.getVerticalScrollBar();
				if (jscrollBar != null)
				jscrollBar.setValue(jscrollBar.getMaximum());//设置滚动条显示位置为滚动棒最大位置处
			}).start();
			scrollcheck.setVisible(true);
			SwingUtilities.updateComponentTreeUI(check);
		}
		if(e.getActionCommand().equals("check")) {
			Component[] jcbs = check.getComponents();
            for (Component component : jcbs) {
                JCheckBox jcb = (JCheckBox) component;
                jcb.setSelected(checkFlag);
            }
            checkFlag = !checkFlag;
			SwingUtilities.updateComponentTreeUI(this);
		}
		if(e.getActionCommand().equals("sql")) {
			//获取数据库设置面板
			DBUI.getInstance();
			//开启一个线程
			new Thread(()->{
				DBUtil.getInstance();
				do {
					dataSource = DBUtil.getSource();
					if (dataSource != null) {
						enableFlag = true;
						break;
					}
					try {
						Thread.sleep(500);//延迟500ms 等待操作完成
						log.info("等待操作完成中...");
					} catch (InterruptedException e1) {
						log.error("获取连接池操作异常",e1);
					}
				} while (dataSource == null);
			}).start();
		}
		if(e.getActionCommand().equals("checkBox")) {
			String packagePath = (String) packageNameBox.getSelectedItem();
			if ("清空列表".equals(packagePath)) {
				LogUtil.clearLog("package");
				Log read = LogUtil.readLog();
				Set<String> list = read.getPackageName();
				packageNameBox.removeAllItems();
		        list.forEach(packName->{
		        	packageNameBox.addItem(packName);
		        });
		        SwingUtilities.updateComponentTreeUI(packageNameBox);
			}
		}
		if(e.getActionCommand().equals("templateCheckBox")) {
			String templatePath = (String) templatePathBox.getSelectedItem();
			if ("清空列表".equals(templatePath)) {
				LogUtil.clearLog("template");
				templatePathBox.removeAllItems();
				defaultTemplate.forEach(template->{
		        	templatePathBox.addItem("内置模板-"+template);
		        });
		        SwingUtilities.updateComponentTreeUI(templatePathBox);
			}
		}
	}
	/**
	 * 获取当前数据库中的全部表
	 */
	public void getAllTables() {
		allTablesList.addAll(DBUtil.getAllTables());
	    //自动设置 行数
	    check.setLayout(new GridLayout((int) Math.ceil(allTablesList.size()/4.0), 8));
        for(String name : allTablesList){
        	JCheckBox checkBox = new JCheckBox(name);
        	checkBox.setSelected(true);
        	checkBox.setActionCommand("");
        	check.add(checkBox);
        }
        checkBtn.setSelected(true);
	}
	/**
	 * 获取被选中的表
	 */
	public void getCheckedTables() {
		checkedList.clear();
		Component[] jcbs = check.getComponents();
        for (Component component : jcbs) {
            JCheckBox jcb = (JCheckBox) component;
            if(jcb.isSelected()) {
                checkedList.add(jcb.getText().trim());
            }
        }
        if(checkedList.size() <= 0){
			JOptionPane.showMessageDialog(this,"请获取需要操作的表");
			return ;
		}
	}
	
	public void checkTemplate() {
		String projectPath = outPathTextField.getText().trim();
		if (StringUtils.isBlank(projectPath)) {
			JOptionPane.showMessageDialog(this,"请输入项目根路径!");
			return ;
		}
		String packagePath = (String) packageNameBox.getSelectedItem(); //packagenameText.getText().trim();
		if(StringUtils.isBlank(packagePath) ){
			JOptionPane.showMessageDialog(this,"请输入项目包名!");
			return ;
		}
		String templatePath = (String) templatePathBox.getSelectedItem();//templatePathTextField.getText().trim();//2020-03-26
			
//		if (StrUtil.isBlank(templatePath)) {
//			JOptionPane.showMessageDialog(this,"请输入模板路径!");
//			return ;
//		}
		Log readLog = LogUtil.readLog();
		readLog.setProjectPath(projectPath);
		
		LogUtil.writeLog(packagePath);
		Log read = LogUtil.readLog();
		Set<String> list = read.getPackageName();
		packageNameBox.removeAllItems();
        list.forEach(packName->{
        	packageNameBox.addItem(packName);
        });
        packageNameBox.addItem("清空列表");
        SwingUtilities.updateComponentTreeUI(packageNameBox);
		if (!templatePath.startsWith("内置模板")) {
			LogUtil.writeTemplateLog(templatePath);
	        mark = new FreeMarkUtil(new File(templatePath));
		}else {
			mark = new FreeMarkUtil(templatePath);
		}
		LogUtil.writeLog(readLog);
		mark.setProjectAbsolutePath(new File(projectPath));
		mark.setPackagePath(packagePath);
		
	}
	/**
	 * 创建Excel
	 */
	@SuppressWarnings("resource")
	public void createExcel(List<String> checkedList) {
		//Excel表头内容
	    String[] colName = {"列名","数据类型","长度","是否为空","默认值","备注"};
	    //Excel表格列宽 ---->根据实际情况调试
	    Integer[] colWidth ={5000,4000,3500,3500,8000,15000};
		try {
			/**
			 * 获取给定类别中使用的表的描述。
			 * 方法原型:ResultSet getAllTables(String catalog,String schemaPattern,String tableNamePattern,String[] types);
			 * catalog - 表所在的类别名称;""表示获取没有类别的列,null表示获取所有类别的列。
			 * schema - 表所在的模式名称(oracle中对应于Tablespace);""表示获取没有模式的列,null标识获取所有模式的列; 可包含单字符通配符("_"),或多字符通配符("%");
			 * tableNamePattern - 表名称;可包含单字符通配符("_"),或多字符通配符("%");
			 * types - 表类型数组; "TABLE"、"VIEW"、"SYSTEM TABLE"、"GLOBAL TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 "SYNONYM";null表示包含所有的表类型;可包含单字符通配符("_"),或多字符通配符("%"); 
			 */
			// 第一步，创建一个webbook，对应一个Excel文件  
		    HSSFWorkbook wb = new HSSFWorkbook(); 
		    List<String> tablesList = DBUtil.getAllTables();
		    area.append("本次共扫描到：---->"+tablesList.size()+" 张表,已选择生成 "+checkedList.size()+"张表");
		    HSSFCellStyle style = wb.createCellStyle(); 
		    style.setAlignment(HorizontalAlignment.CENTER);//垂直
		    style.setVerticalAlignment(VerticalAlignment.CENTER);//水平
		    style.setBorderBottom(BorderStyle.THIN);
		    style.setBorderRight(BorderStyle.THIN);
		    style.setBorderLeft(BorderStyle.THIN);
		    style.setBorderTop(BorderStyle.THIN);
		    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
		    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
		    style.setTopBorderColor(IndexedColors.BLACK.getIndex());
		    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
//			    style.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
		    style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
		    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		    
		    HSSFCellStyle fstyle = wb.createCellStyle();
		    fstyle.cloneStyleFrom(style);
		    fstyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
		    tablesList.forEach(tableName->{
//				log.info("表名：" + tableName);
//				log.info("列名称:"+"\t列类型:" +"\t长度:"+"\t是否为空:"+"\t默认值:"+"\t注释:");  
				if(enableFlag == checkTable(checkedList,tableName)){
					area.append(Config.LF+"表名：" + tableName);
					area.append(Config.LF+"  列名称:"+"\t列类型:" +"\t长度:"+"\t是否为空:"+ "\t默认值:"+"\t注释:");
					
					// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet  
				    HSSFSheet sheet = wb.createSheet(tableName);  
				    // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
				    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));//合并第一行单元格
				    //Excel表格样式 调试非常麻烦，不建议修改
				    HSSFRow first = sheet.createRow((int) 0); 
				    
				    first.createCell(0).setCellValue("表名: "+tableName);
				    first.getCell(0).setCellStyle(fstyle);
				    HSSFRow row = sheet.createRow((int) 1);  
				    HSSFCell cell = null;
				    HSSFCellStyle sstyle = wb.createCellStyle();
				    sstyle.cloneStyleFrom(style);
				    sstyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
			    
				    // 第四步，创建单元格，并设置值表头 设置表头居中  
				    for(int i=0;i< colName.length;i++){
				    	cell = row.createCell((short) i);  
					    cell.setCellValue(colName[i]);  
					    cell.setCellStyle(sstyle); 
					    sheet.setColumnWidth(i, colWidth[i]); //调整第i列宽度
					/**列宽自动调整解决方案*/
					/** sheet.autoSizeColumn(i); （版本不能太老） 
						sheet.autoSizeColumn(i, true);（合并的单元格使用） 
						sheet.setColumnWidth(i, “列名”.getBytes().length*2*256);（中文适用）
						sheet.AutoSizeColumn(i);
						只能解决英文、数字列宽自适应，如果该列为中文，会出现列宽不足现象。
						可通过手动设置列宽解决
						首先通过value.getBytes().length方法对比找到该列数据最大长度
						通过sheet.setColumnWidth(i,cellLength*2*256);手动设置列宽。
						长度乘以2是为了解决纯数字列宽度不足会显示科学计数法问题，乘以256得到的数据才是excel真实列宽。
					*/
				    }

			        //实际情况可能有联合主键
			        List<String> pkStr = new ArrayList<>();
			        pkStr.clear();
			        boolean enableFlag = false;
					
//					log.info("主键: " + pkStr.toString()+"主键数量: "+pkStr.size());
					enableFlag = (pkStr.size()>1)?true:false;
					int i = 1;
					
					List<TableInfo> tableInfo = DBUtil.getTableInfo(tableName); 
//					for(Temp columns:tableInfo){
						for(int h = 0;h<tableInfo.size();h++){
							TableInfo columns = tableInfo.get(h);
						row = sheet.createRow((int) i + 1); 
				        // 第四步，创建单元格，并设置值  
						
						String colname = columns.getColName();
						String columnType = columns.getColType();
						String isNullable = columns.getIsNull();
						String precision = columns.getPrecision();
						String defaultValue = columns.getDefaultVal();
						String remarks = columns.getRemark();
						
						if(pkStr.size()!= 0){
					        if(!enableFlag){
					        	remarks = (i==1?(colname.equals(pkStr.get(0))?"主键 "+remarks:""+remarks):remarks); 
					        }else{
						        for(int a=0;a<pkStr.size();a++){
						        	if(colname.equals(pkStr.get(a))){
						        		remarks = ("主键 "+remarks);break;
						        	} else{
						        		remarks = (" "+remarks);
						        	}
						        }
					        }
						}
				        row.createCell((short) 0).setCellValue(colname);
				        row.createCell((short) 1).setCellValue(columnType);  
				        row.createCell((short) 2).setCellValue(precision);  
				        row.createCell((short) 3).setCellValue(isNullable);  
				        row.createCell((short) 4).setCellValue(defaultValue); 
				        row.createCell((short) 5).setCellValue(remarks);
				        
//				        if(pkStr.size()!= 0)
				        for(int k=0;k<=5;k++)row.getCell(k).setCellStyle(style); 
		                log.debug(colname+"\t" + columnType.toLowerCase()+"\t"+ precision+"\t"+ isNullable+"\t"+defaultValue+",注释: "+remarks);   
		                area.append(Config.LF+"  "+colname+"\t" + columnType.toLowerCase()+"\t"+ precision+"\t"+ isNullable+"\t"+defaultValue+"\t"+remarks);
		                area.selectAll();
		                i++;
		                
					}//foreach
				}//if
			});//for
			String savepath = outPathTextField.getText();
			if(savepath == null || "".equals(savepath)){
				savepath = "D:/auxiliarytool/";
			}
			savepath = savepath+File.separator+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+Config.SUFFIX_XLS;
			
			if(enableFlag && checkedList.size()>0){
				FileOutputStream fout = new FileOutputStream(savepath,true); 
				wb.write(fout);  
				if (fout != null) {
					fout.close(); 
				}
				this.checkedList.clear();
				area.append(Config.LF+"文件已保存至："+savepath+Config.LF);
			}
		} catch (Exception e) {
			log.error("",e);
		} 
	}
	/**
	 * 判断需要打印的表格
	 * @return
	 */
	public boolean checkTable(List<String> checked,String currentTable) {
		if (checked.contains(currentTable)) {
			return true;
		}
		return false;
	}

}
